﻿using System;
using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Reporting;
using HappyBa.Core.UserReport;
using HappyBa.Localization;
using Mnk.Library.Common.Log;
using Mnk.Library.Common.MT;
using Mnk.Library.WpfControls.Dialogs;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for UsersStatistics.xaml
    /// </summary>
    public partial class UsersStatisticsPage
    {
        private readonly ILog log = LogManager.GetLogger<StatisticsPage>();
        private readonly IUsersReportGenerator builder;
        private readonly IUserStatisticsCalculator calculator;
        private readonly Config config;

        public UsersStatisticsPage()
        {
            InitializeComponent();
            var container = ((MainWindow)Application.Current.MainWindow).Container;
            builder = container.GetInstance<IUsersReportGenerator>();
            calculator = container.GetInstance<IUserStatisticsCalculator>();
            config = container.GetInstance<Config>();
        }

        private void BuildClick(object sender, RoutedEventArgs e)
        {
            if (config.Current == null) return;

            DialogsCache.ShowProgress(
                Collect,
                HappyBaLang.CollectProjectsInformation,
                Application.Current.MainWindow,
                false);
        }

        private void Collect(IUpdater updater)
        {
            try
            {
                var context = new UserReportContext
                {
                    Settings = config.Current.UsersAnalisys.Clone(),
                    Users = config.Current.ActiveEmployees.Select(x => x.Key).ToArray()
                };
                var report = calculator.BuildReport(context).ToArray();
                updater.Update(0.5f);
                builder.Build(context, report);
            }
            catch (Exception ex)
            {
                log.Write(ex, "Can't calculate statistics");
            }
        }
    }
}
